import random

import logging
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from verifications import constants
from verifications.serializers import ImageCodeCheckSerializer
from .migrations.captcha.captcha import captcha
from django_redis import get_redis_connection

from meiduo_mall.libs.yuntongxun.sms import CCP

# 创建日志对象
logger = logging.getLogger('django')


# 图片验证码类
class ImageCodeView(APIView):
    def get(self,request,image_code_id):
        """返回图片验证码"""
        # 1.获取参数

        # 2/校验参数
        # print(image_code_id)
        # 3.生成图片验证码
        text,image_code = captcha.generate_captcha()
        # 4.保存图片文字
        image_redis = get_redis_connection('verify_codes')
        image_redis.setex("image_%s" %image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 5.返回图片验证码给前端
        # 因为rest_framework提供的Response会渲染一下
        return HttpResponse(image_code,content_type='image/jpeg')


class SMSCodeView(GenericAPIView):
    """
    短信验证码
    传入参数：
        mobile,  image_code_id, text
    """
    # 需要校验参数－－所以使用序列化器
    # 定义序列化器
    serializer_class = ImageCodeCheckSerializer

    def get(self,request,mobile):
        # 接受参数
        serializer = self.get_serializer(data = request.query_params)
        # 校验参数
        serializer.is_valid(raise_exception = True)

        # 生成短信验证码
        text = '%06d' % random.randint(0, 999999)
        print(text)

        # 保存短信验证码的内容
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex('image_%s' %mobile,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        # # 保存是否发送短信的记录
        # redis_conn.setex('send_flag_%s' %mobile,constants.IMAGE_CODE_REDIS_EXPIRES,1)

        # 创建管道－－减少与ｒｅｄｉｓ数据库的交互，提升性能
        # 注意：管道只能进行写入－－不支持读取
        pl = redis_conn.pipeline()
        pl.setex('image_%s' % mobile, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        pl.setex('send_flag_%s' % mobile, constants.IMAGE_CODE_REDIS_EXPIRES, 1)
        # execute方法将创建的ｒｅｄｉｓ语句执行
        pl.execute()

        # 组织短信验证码内容
        ccp = CCP()
        time = constants.SMS_CODE_REDIS_EXPIRES // 60
        # 发送短信验证码
        try:
            result = ccp.send_template_sms('18672698722', [text, time], 1)
        except Exception as e:
            logger.error("短信发送异常：%s, 失败原因：%s" %(mobile,e))
            return Response({'message':"发送失败"},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            if result == '-1':
                logger.error("短信发送失败：%s" % mobile)
                return Response({'message': "fail"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            else:
                return Response({'message':'OK'})



